"""
Agent管理器 - 统一管理所有Agent实例
"""
from typing import Dict, Optional
from agent.OpenaiAssistantAgent import OpenaiAssistantAgent
from core.prompt_manager import prompt_manager
from config.yaml_settings import get_llm_model_config, get_llm_api_config, LLMModelConfig, LLMAPIConfig


class AgentManager:
    """Agent管理器 - 单例模式"""
    
    _instance = None
    _initialized = False
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self):
        if not self._initialized:
            self.agents = {}
            self._initialized = True
    
    def get_analysis_agent(self, 
                          api_key: Optional[str] = None,
                          base_url: Optional[str] = None,
                          model_config: Optional[LLMModelConfig] = None,
                          api_config: Optional[LLMAPIConfig] = None) -> OpenaiAssistantAgent:
        """获取分析Agent实例（单例）"""
        agent_key = "analysis_agent"
        
        if agent_key not in self.agents:
            # 使用传入的配置或默认配置
            if api_config is None:
                api_config = get_llm_api_config()
            if model_config is None:
                model_config = get_llm_model_config()
            
            # 从提示词管理器加载系统消息
            system_message = prompt_manager.load_prompt("analysis_system")
            
            agent = OpenaiAssistantAgent(
                name="report_analysis_agent",
                api_key=api_key or api_config.api_key,
                base_url=base_url or api_config.base_url,
                system_message=system_message,
                model_config=model_config,
                api_config=api_config
            )
            
            self.agents[agent_key] = agent
            print(f"创建新的Agent实例: {agent_key}")
        
        return self.agents[agent_key]
    
    def get_chart_agent(self,
                       api_key: Optional[str] = None,
                       base_url: Optional[str] = None,
                       model_config: Optional[LLMModelConfig] = None,
                       api_config: Optional[LLMAPIConfig] = None) -> OpenaiAssistantAgent:
        """获取图表Agent实例（单例）"""
        agent_key = "chart_agent"
        
        if agent_key not in self.agents:
            # 使用传入的配置或默认配置
            if api_config is None:
                api_config = get_llm_api_config()
            if model_config is None:
                model_config = get_llm_model_config()
            
            # 从提示词管理器加载系统消息
            system_message = prompt_manager.load_prompt("chart_system")
            
            agent = OpenaiAssistantAgent(
                name="chart_generation_agent",
                api_key=api_key or api_config.api_key,
                base_url=base_url or api_config.base_url,
                system_message=system_message,
                model_config=model_config,
                api_config=api_config
            )
            
            self.agents[agent_key] = agent
            print(f"创建新的Agent实例: {agent_key}")
        
        return self.agents[agent_key]
    
    def get_agent_info(self) -> Dict[str, any]:
        """获取Agent信息"""
        return {
            "available_agents": list(self.agents.keys()),
            "agent_count": len(self.agents),
            "status": "initialized" if self._initialized else "not_initialized"
        }


# 全局单例实例
agent_manager = AgentManager()